import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'
import {Message} from "element-ui";

const getDefaultState = () => {
  return {
    token: localStorage.getItem('USER_TOKEN'),
    name: '',
    avatar: ''
  }
}

const state = {
  token: localStorage.getItem('USER_TOKEN'),
  name: '',
  avatar: '',
  buttons: [],
  roles: [],
  asyncRoutes: [],//准备放用户返回的字符串信息对应的真正的异步路由数组
  routes: [] //代表这个用户对应的所有的路由数组,用于后期根据它动态生成菜单去用(v-for)
}
const mutations = {
  RESET_STATE(state) {
    state.token = ""
    state.name = ''
    state.avatar = ''
  },
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USERINFO(state, userInfo) {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.buttons = userInfo.buttons
    state.roles = userInfo.roles
  }
}
const actions = {
  async login({commit}, userInfo) {
    try {
      const result = await login(userInfo)
      if (result.code === 200 || result.code === 20000) {
        commit('SET_TOKEN', result.data.token)
        localStorage.setItem('USER_TOKEN', result.data.token)
      }
    } catch (error) {
      Message.error('登录请求失败')
    }
  },
  async getInfo({commit}, state) {
    const result = await getInfo(state.token)
    try {
      if (result.code === 200 || result.code === 20000) {
        if (!result.data.token) {
          return Promise.reject('登录已过期,请重新登录')
        }
        commit('SET_USERINFO', result.data.token)
      }
    } catch (error) {
      Message.error('获取用户名或密码失败')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

